/**
* ClassName: BusinessInfo
* Package: src/views
* Description: 商家信息页面
*
* @Author Liu Wenrui
* @Create 2025/9/25 16:01
* @Version 1.1
*
* @Author Liu Wenrui
* @Create 2025/9/25 17:45
* @Version 1.2
*
* @Author Liu Wenrui
* @Create 2025/9/25 21:30
* @Version 1.3
*/

<template>
    <div class="wrapper">

        <!-- header部分 -->
        <header>
            <span class="back-btn" @click="goBack">&#8592;</span>
            <p>商家列表</p>
        </header>
        <!-- 商家列表部分 -->
        <ul class="business">
            <li v-for="item in businessArr" :key="item.businessId || item.id" @click="toBusinessInfo(item.businessId)">
                <div class="business-img">
                    <img :src="getBusinessImg(item.businessImg)">
                    <div class="business-img-quantity" v-show="item.quantity > 0">
                        {{ item.quantity }}
                    </div>
                </div>
                <div class="business-info">
                    <h3>{{ item.businessName }}</h3>
                    <p>&#165;{{ item.startPrice }}起送 | &#165;{{ item.deliveryPrice }}配送</p>
                    <p>{{ item.businessExplain }}</p>
                </div>
                <span class="favorite-star" :class="{ filled: item.isFavorite }" @click.stop="toggleFavorite(item)"
                    title="收藏">
                    <svg viewBox="0 0 24 24" width="28" height="28">
                        <polygon class="star-polygon" stroke="#FFD700" stroke-width="2"
                            points="12,2 15,9 22,9 17,14 19,21 12,17 5,21 7,14 2,9 9,9" />
                    </svg>
                </span>
            </li>
        </ul>
        <!-- 底部菜单部分 -->
        <Footer></Footer>
    </div>
</template>

<script>
import Footer from '../components/Footer.vue';
export default {
    name: 'BusinessList',
    data() {
        return {
            orderTypeId: this.$route.query.orderTypeId,
            businessArr: [],
            user: {}
        }
    },
    created() {
        // 分类查询：返回列表
        this.$axios.get('/businesses/by-order-type', { params: { orderTypeId: this.orderTypeId } })
            .then(response => {
                const list = Array.isArray(response.data?.data) ? response.data.data : []
                this.businessArr = list.map(b => ({
                    ...b,
                    businessId: b.businessId || b.id,
                    isFavorite: false,
                    starId: null,
                    quantity: 0
                }))
                const token = sessionStorage.getItem('token')
                if (token) {
                    this.listCart()
                    this.$axios.get('/star').then(res => {
                        const stars = res.data?.data || []
                        this.businessArr.forEach(item => {
                            const star = stars.find(s => s.businessId === (item.businessId || item.id))
                            if (star) {
                                item.isFavorite = true
                                item.starId = star.id
                            }
                        })
                    })
                }
            })
            .catch(console.error)
    },
    components: {
        Footer
    },
    methods: {
        getBusinessImg(img) {
            // 网络图片直接返回
            if (img && (img.startsWith('http://') || img.startsWith('https://'))) {
                return img;
            }
            // 本地图片用 require
            try {
                return require('../assets/' + img);
            } catch (e) {
                // 图片不存在时返回默认图片
                return require('../assets/default.png');
            }
        },
        listCart() {
            console.log('businessArr before listing cart:', this.businessArr);
            this.$axios.get('/carts/current-user').then(response => {
                let cartArr = response.data.data || [];
                for (let businessItem of this.businessArr) {
                    businessItem.quantity = 0;
                    for (let cartItem of cartArr) {
                        if (cartItem.businessId == businessItem.businessId) {
                            businessItem.quantity += cartItem.quantity;
                        }
                    }
                }
                this.businessArr.sort();
            }).catch(error => {
                console.error(error);
            });
        },
        toBusinessInfo(businessId) {
            this.$router.push({ path: '/businessInfo', query: { businessId } });
        },
        goBack() {
            this.$router.back();
        },
        async toggleFavorite(item) {
            const businessId = item.businessId;
            if (item.isFavorite) {
                // 取消收藏
                try {
                    let starId = item.starId
                    if(!starId) {
                        const { data } = await this.$axios.get(`/star/by-business/${businessId}`)
                        starId = data?.data?.id
                    }
                    if(!starId) {
                        throw new Error('Star ID not found');
                    }
                    await this.$axios.delete(`/star/${starId}`);
                    item.isFavorite = false;
                    item.starId = null;
                } catch (e) {
                    alert('取消收藏失败！');
                    return;
                }
            } else {
                // 收藏
                try {
                    const { data } = await this.$axios.post(`/star`, { businessId });
                    item.isFavorite = true;
                    console.log('Star created with ID:', data?.data?.id);
                    item.starId = data?.data?.id;
                } catch (e) {
                    alert('收藏失败！');
                    return;
                }
            }
        }
    }
}
</script>
<style scoped>
/****************** 总容器 ******************/
.wrapper {
    width: 100%;
    height: 100%;
}

/****************** header部分 ******************/
.wrapper header {
    width: 100%;
    height: 12vw;
    background-color: #0097FF;
    color: #fff;
    font-size: 4.8vw;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1000;
    display: flex;
    justify-content: center;
    align-items: center;
}

.back-btn {
    position: absolute;
    left: 3vw;
    top: 50%;
    transform: translateY(-50%);
    font-size: 4vw;
    cursor: pointer;
    color: #fff;
    z-index: 1001;
    padding: 0 1vw;
    user-select: none;
}

/****************** 商家列表部分 ******************/
.wrapper .business {
    width: 100%;
    margin-top: 12vw;
    margin-bottom: 14vw;
}

.wrapper .business li {
    position: relative;
    width: 100%;
    box-sizing: border-box;
    padding: 2.5vw;
    border-bottom: solid 1px #DDD;
    user-select: none;
    cursor: pointer;
    display: flex;
    align-items: center;
}

.wrapper .business li .business-img {
    /*这里设置为相当定位，成为business-img-quantity元素的父元素*/
    position: relative;
}

.wrapper .business li .business-img img {
    width: 20vw;
    height: 20vw;
}

.wrapper .business li .business-img .business-img-quantity {
    width: 5vw;
    height: 5vw;
    background-color: red;
    color: #fff;
    font-size: 3.6vw;
    border-radius: 2.5vw;
    display: flex;
    justify-content: center;
    align-items: center;
    /*设置成绝对定位，不占文档流空间*/
    position: absolute;
    right: -1.5vw;
    top: -1.5vw;
}

.wrapper .business li .business-info {
    margin-left: 3vw;
}

.wrapper .business li .business-info h3 {
    font-size: 3.8vw;
    color: #555;
}

.wrapper .business li .business-info p {
    font-size: 3vw;
    color: #888;
    margin-top: 2vw;
}

.favorite-star {
    position: absolute;
    right: 2vw;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
    z-index: 10;
    transition: transform 0.2s;
    font-size: 5vw;
    /* 让SVG更大更明显 */
    display: flex;
    align-items: center;
}

.favorite-star svg {
    display: block;
}

.favorite-star:hover {
    transform: scale(1.15);
}

.favorite-star .star-polygon {
    fill: none;
    transition: fill 0.2s;
}

.favorite-star.filled .star-polygon {
    fill: #FFD700;
}
</style>